<?php

namespace App\Http\Controllers;
use DB;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class NewssController extends Controller
{
    //
    public function index()
    {
    	$res = DB::table('news')->get();
        return view('newss.index',['res'=>$res]);
    }
    public function add()
    {
    	return view('newss.add');
    }

    public function insert(Request $request)
    {
    	 $res = $request->except('_token','logo');

        if($request->hasFile('logo')){

            $name = time().rand(1000,9999);
            $suffix = $request->file('logo')->getClientOriginalExtension();

            $request->file('logo')->move('./upload',$name.'.'.$suffix);

            $res['logo'] = '/upload/'.$name.'.'.$suffix;
        }

        $res['addtime'] = date('Y-m-d H:i:s',time());
        $data = DB::table('news')->insert($res);
        if($data){
            return redirect('/newss/index');
        }
    }

    public function edit($id)
    {
    	$res = DB::table('news')->where('id',$id)->first();

        return view('newss.edit',['res'=>$res]);
    }

    public function update(Request $request,$id)
    {
    	 $res = $request->except('_token','logo');

        if($request->hasFile('logo')){

            $name = time().rand(1000,9999);
            $suffix = $request->file('logo')->getClientOriginalExtension();

            $request->file('logo')->move('./upload',$name.'.'.$suffix);

            $res['logo'] = '/upload/'.$name.'.'.$suffix;
        }

        $res['addtime'] = date('Y-m-d H:i:s',time());
        $data = DB::table('news')->where('id',$id)->update($res);
        if($data){
            return redirect('/newss/index');
        }else{
            return back();
        }
    }

    public function delete($id)
    {
    	$res = DB::table('news')->where('id',$id)->delete();

       if(!$res){
        return redirect('/home/news');
       }else{
        return back();
       }
    }
    
}
